package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.asn1.axdr.AxdrOctetString;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * SID类
 * 实现安全标识符的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class SID implements AxdrType {

    private byte[] dataCode = null;
    private Unsigned32 indi = null;
    private AxdrOctetString fdata = null;

    /**
     * 默认构造函数
     */
    public SID() {
    }

    /**
     * 设置数据编码
     * 
     * @param dataCode 数据编码
     */
    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    /**
     * 设置SID参数
     * 
     * @param indi  标识符
     * @param fdata 数据
     */
    public void setAll(Unsigned32 indi, AxdrOctetString fdata) {
        this.indi = indi;
        this.fdata = fdata;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        int codeLength = 0;

        indi = new Unsigned32();
        indi.setConst();
        codeLength += indi.decode(input);

        fdata = new AxdrOctetString();
        codeLength += fdata.decode(input);

        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength;

        if (dataCode != null) {
            codeLength = dataCode.length;
            for (int i = dataCode.length - 1; i >= 0; i--) {
                try {
                    output.write(dataCode[i]);
                } catch (java.io.IOException e) {
                    throw new RuntimeException(e);
                }
            }
        } else {
            if (indi != null && fdata != null) {
                codeLength = 0;
                codeLength += fdata.encode(output);
                codeLength += indi.encode(output);
            } else {
                throw new RuntimeException("fdata || indi is null");
            }
        }
        return codeLength;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        try {
            encode(revOStream);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("Error encoding SID", e);
        }
        this.dataCode = revOStream.getArray();
    }

    /**
     * 获取标识符
     * 
     * @return 标识符
     */
    public Unsigned32 getIndi() {
        return indi;
    }

    /**
     * 获取数据
     * 
     * @return 数据
     */
    public AxdrOctetString getFdata() {
        return fdata;
    }

    @Override
    public String toString() {
        if (indi != null && fdata != null) {
            return "sequence: {" + "indi: " + indi + ", fdata: " + fdata + "}";
        } else {
            return "indi || fdata is null";
        }
    }
}